import React, { Component, createRef } from 'react';
import { SafeAreaView, View, Text, Image, StyleSheet, TouchableOpacity, FlatList, CheckBox, Alert } from 'react-native';
import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import HttpUtil from '../util/HttpUtil';
import {
    AssetTableName, InventoryTableName, MoveReasonTableName, queryAll,
    insertList, MoveLocationTableName, deleteById, insertDataCenterRoomTree,
    deleteAll, DatacenterRoomTableName, insertBrandModelTree,
    UserTableName, DepartmentTableName, insertDepartmentTree,
    ConfigTableName, BrandModelTableName, TypeTableName, queryByCondition,
    insert, InventoryDetailTableName, InventoryMoreOutTableName, queryInventoryDetail
} from '../util/RealmUtil';
import { RRCLoading, RRCToast } from 'react-native-overlayer';
import BaseComponent from '../component/BaseComponent';
import DeviceInfo from 'react-native-device-info';
import { set } from 'react-native-reanimated';
import { v4 as uuidv4 } from 'uuid';
export default class DataSync extends BaseComponent {
    constructor(props) {
        super(props);
        this.textFlatListRef = createRef();
        this.state = {
            checkBoxData: [
                { key: InventoryTableName, label: '资产盘点', isChecked: true },
                { key: MoveLocationTableName, label: '位置迁移', isChecked: true },
                { key: AssetTableName, label: '资产数据', isChecked: true },
                { key: 'BaseData', label: '基础数据', isChecked: true },
            ],
            syncHintText: [],

        };
        RRCLoading.setLoadingOptions({
            text: '同步数据中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
            loadingTextStyle: {}
        })
    }
    componentDidMount() {
        this.init();
    }
    init = () => {
        // queryAll(MoveLocationTableName).then((data) => {
        //     console.log("位置迁移:" + JSON.stringify(data));
        // }).catch((err) => {
        //     console.log(err);
        // });
        // queryByCondition(DatacenterRoomTableName, 'isRoot', true).then((data) => {
        //     console.log("数据中心树:" + JSON.stringify(data));
        // }).catch((err) => {
        //     console.log(err);
        // });

        // queryByCondition(DepartmentTableName, 'isRoot', true).then((data) => {
        //     console.log("部门树:" + JSON.stringify(data));
        // }).catch((err) => {
        //     console.log(err);
        // });

        // queryByCondition(BrandModelTableName, 'isRoot', true).then((data) => {
        //     console.log("品牌型号树:" + JSON.stringify(data));
        // }).catch((err) => {
        //     console.log(err);
        // });
    }
    submit = () => {
        let data = this.state.checkBoxData;
        let syncData = [];
        for (let i = 0; i < data.length; i++) {
            if (data[i].isChecked) {
                syncData.push(data[i]);
            }
        }
        if (syncData.length === 0) {
            RRCToast.show('请选择要同步的数据');
            return;
        }
        Alert.alert(
            '提示',
            '同步数据会上传并清空本地数据,确定同步吗？',
            [
                { text: '取消', onPress: () => console.log('Cancel Pressed'), style: 'cancel' },
                { text: '确定', onPress: () => this.syncData(syncData) },
            ],
            { cancelable: false }
        )
    }
    changeHindText = (text, isError) => {
        const newArray = [...this.state.syncHintText];
        // 将新元素添加到数组的第一个位置
        newArray.unshift({ text: text, isError: isError });
        this.setState({ syncHintText: newArray });
        this.textFlatListRef.current.scrollToIndex({ index: 0, animated: true });
    }
    syncData = async (syncData) => {
        this.setState({ syncHintText: [] });
        syncData.forEach(async item => {
            if (item.key === InventoryTableName) {
                await this.syncInventoryData();
            } else if (item.key === MoveLocationTableName) {
                await this.syncMoveReasonData();
            } else if (item.key === AssetTableName) {
                await this.syncAssetData();
            } else if (item.key === 'BaseData') {
                await this.syncBaseData();
            }

        });
    }
    // 同步资产数据
    syncAssetData = async () => {
        await HttpUtil.post('qryAllAssets', {}).then(async result => {
            if (result.httpCode === 200) {
                let data = result.data;
                // 保存资产数据
                await this.saveAssetData(data);
            } else {
                this.changeHindText('[资产数据]:同步资产数据错误:' + result.msg + '', true);
            }
        }).catch((err) => {
            this.changeHindText('[资产数据]:同步资产数据错误:' + err + '', true);
        });
    }


    // 同步基础数据
    syncBaseData = async () => {
        await HttpUtil.post('basicData', {}).then(async result => {
            if (result.httpCode === 200) {
                let data = result.data;
                // 保存迁移原因数据
                await this.saveMoveReasonData(data);
                // 保存机房数据
                await this.saveDataCenterRoomTree(data);
                // 保存部门数据
                await this.saveDepartmentTree(data);
                // 保存用户数据
                await this.saveUserData(data);
                // 保存配置数据
                await this.saveConfigData(data);
                // 保存类型数据
                await this.saveTypeData(data);
                // 保存品牌型号数据
                await this.saveBrandModelTree(data);
            } else {
                this.changeHindText('[基础数据]:同步基础数据错误:' + result.msg + '', true);
            }
        }).catch((err) => {
            this.changeHindText('[基础数据]:同步基础数据错误:' + err + '', true);
        });
    }
    // 保存类型数据
    saveTypeData = async (data) => {
        if (data.typeVo && data.typeVo.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地类型数据');
            deleteAll(TypeTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地类型数据成功');
                this.changeHindText('[基础数据]:保存类型数据到本地');
                insertList(TypeTableName, data.typeVo).then(() => {
                    this.changeHindText('[基础数据]:类型数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:类型数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地类型数据失败:' + err + '', true);
            });

        } else {
            this.changeHindText('[基础数据]:从服务器同步的类型数据为空');
        }
    }


    // 保存品牌型号树
    saveBrandModelTree = async (data) => {
        if (data.brandModelTree && data.brandModelTree.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地品牌型号数据');
            deleteAll(BrandModelTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地品牌型号数据成功');
                this.changeHindText('[基础数据]:保存品牌型号数据到本地');
                insertBrandModelTree(data.brandModelTree).then(() => {
                    this.changeHindText('[基础数据]:品牌型号数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:品牌型号数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地品牌型号数据失败:' + err + '', true);
            });

        } else {
            this.changeHindText('[基础数据]:从服务器同步的品牌型号树数据为空');
        }
    }

    // 保存配置数据
    saveConfigData = async (data) => {
        if (data.remarkList && data.remarkList.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地配置数据');
            deleteAll(ConfigTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地配置数据成功');
                this.changeHindText('[基础数据]:保存配置数据到本地');
                insertList(ConfigTableName, data.remarkList).then(() => {
                    this.changeHindText('[基础数据]:配置数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:配置数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地配置数据失败:' + err + '', true);
            });
        } else {
            this.changeHindText('[基础数据]:从服务器同步的配置数据为空');
        }
    }


    // 保存用户数据
    saveUserData = async (data) => {
        if (data.userList && data.userList.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地用户数据');
            deleteAll(UserTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地用户数据成功');
                this.changeHindText('[基础数据]:保存用户数据到本地');
                insertList(UserTableName, data.userList).then(() => {
                    this.changeHindText('[基础数据]:用户数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:用户数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地用户数据失败:' + err + '', true);
            });

        } else {
            this.changeHindText('[基础数据]:从服务器同步的用户数据为空');
        }
    }


    // 保存部门数据
    saveDepartmentTree = async (data) => {
        if (data.departmentTree && data.departmentTree.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地部门数据');
            deleteAll(DepartmentTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地部门数据成功');
                this.changeHindText('[基础数据]:保存部门数据到本地');
                insertDepartmentTree(data.departmentTree).then(() => {
                    this.changeHindText('[基础数据]:部门数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:部门数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地部门数据失败:' + err + '', true);
            });
        } else {
            this.changeHindText('[基础数据]:从服务器同步的部门数据为空');
        }
    }

    // 保存数据中心机房数据
    saveDataCenterRoomTree = async (data) => {
        if (data.datacenterRoomTree && data.datacenterRoomTree.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地机房数据');
            deleteAll(DatacenterRoomTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地机房数据成功');
                this.changeHindText('[基础数据]:保存机房数据到本地');
                insertDataCenterRoomTree(data.datacenterRoomTree).then(() => {
                    this.changeHindText('[基础数据]:机房数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:机房数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地机房数据失败:' + err + '', true);
            });
        } else {
            this.changeHindText('[基础数据]:从服务器同步的机房数据为空');
        }
    }

    // 保存资产数据
    saveAssetData = async (data) => {
        if (data && data.length > 0) {
            //清空本地数据
            this.changeHindText('[资产数据]:正在删除本地资产数据');
            deleteAll(AssetTableName).then(() => {
                this.changeHindText('[资产数据]:删除本地资产数据成功');
                this.changeHindText('[资产数据]:保存资产数据到本地');
                insertList(AssetTableName, data).then(() => {
                    this.changeHindText('[资产数据]:资产数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[资产数据]:资产数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[资产数据]:删除本地资产数据失败:' + err + '', true);
            });
        } else {
            this.changeHindText('[资产数据]:从服务器同步的资产数据为空');
        }
    }

    saveMoveReasonData = async (data) => {
        if (data.moveReasonList && data.moveReasonList.length > 0) {
            // 清空本地数据
            this.changeHindText('[基础数据]:正在删除本地迁移原因数据');
            deleteAll(MoveReasonTableName).then(() => {
                this.changeHindText('[基础数据]:删除本地迁移原因数据成功');
                this.changeHindText('[基础数据]:保存迁移原因数据到本地');
                insertList(MoveReasonTableName, data.moveReasonList).then(() => {
                    this.changeHindText('[基础数据]:迁移原因数据保存本地成功');
                }).catch((err) => {
                    this.changeHindText('[基础数据]:迁移原因数据保存本地失败:' + err + '', true);
                });
            }).catch((err) => {
                this.changeHindText('[基础数据]:删除本地迁移原因数据失败:' + err + '', true);
            });
        } else {
            this.changeHindText('[基础数据]:从服务器同步的迁移原因数据为空');
        }
    }


    // 同步盘点单数据
    syncInventoryData = async () => {
        // 先上传本地数据
        await queryAll(InventoryTableName).then(async (data) => {
            console.log("盘点单:" + JSON.stringify(data));
            if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    await queryInventoryDetail(item.id_).then(async (detail) => {
                        detail.id = detail.id_
                        if(detail.moreOutList && detail.moreOutList.length > 0){
                            let moreOutList = [];
                            detail.moreOutList.forEach((moreOutItem) => {
                                moreOutList.push({rfidNo:moreOutItem.rfidNo});
                            });
                            detail.moreOutList = moreOutList;
                        }
                        await HttpUtil.post('syncInventory', detail).then((result) => {
                            console.log("上传盘点单结果:" + JSON.stringify(result));
                            if (result && result.httpCode == 200) {
                                this.changeHindText('[资产盘点]:盘点单[' + item.inventoryName + ']上传成功');
                            }
                        }).catch((err) => {
                            this.changeHindText('[资产盘点]:盘点单[' + item.inventoryName + ']上传失败:' + err + '', true);
                        });
                    }).catch((err) => {
                        this.changeHindText('[资产盘点]:查询本地数据错误:' + err + '', true);
                    });
                }

            } else {
                this.changeHindText('[资产盘点]:没有需要上传的数据');
            }
            this.changeHindText('[资产盘点]:正在删除本地盘点单数据');
            await deleteAll(InventoryTableName).then(() => { }).catch((err) => { });
            await deleteAll(InventoryDetailTableName).then(() => { }).catch((err) => { });
            await deleteAll(InventoryMoreOutTableName).then(() => { }).catch((err) => { });
            this.changeHindText('[资产盘点]:删除本地盘点单数据成功');
            // 再下载服务器数据
            await this.downloadInventorySheet();
        }).catch((err) => {
            this.changeHindText('[资产盘点]:查询本地数据错误:' + err + '', true);
        });
    }
    //下载盘点单
    downloadInventorySheet = async () => {
        let params = {
            pageNum: 1,
            pageSize: 999999999,
        }
        await HttpUtil.post('downloadInventorySheet', params).then(result => {
            if (result.httpCode === 200) {
                this.changeHindText('[资产盘点]:获取盘点单数据成功');
                console.log(JSON.stringify(result.data));
                this.saveInventoryData(result.data);
            } else {
                this.changeHindText('[资产盘点]:获取盘点单数据失败:' + result.msg + '', true);
            }
        }).catch((err) => {
            this.changeHindText('[资产盘点]:获取盘点单数据失败:' + err + '', true);
        });
    }
    // 保存盘点单数据
    saveInventoryData = async (data) => {
        if (data && data.length > 0) {
            data.forEach((item, index) => {
                if (item.detailList && item.detailList.length > 0) {
                    // 插入盘点详情数据
                    item.detailList.forEach((detailItem) => {
                        detailItem.inventoryId = item.id_;
                    });
                    insertList(InventoryDetailTableName, item.detailList).then(() => {
                        this.changeHindText('[资产盘点]:盘点单[' + item.inventoryName + ']详情数据保存本地成功');
                    }).catch((err) => {
                        this.changeHindText('[资产盘点]:盘点单[' + item.inventoryName + ']详情数据保存本地失败:' + err + '', true);
                    });
                }
                if (item.moreOutList && item.moreOutList.length > 0) {
                    // 插入盘点详情数据
                    item.moreOutList.forEach((moreOutItem) => {
                        const id = uuidv4().replace(/-/g, '');
                        moreOutItem.id = id,
                            moreOutItem.inventoryId = item.id_;
                    });
                    insertList(InventoryMoreOutTableName, item.moreOutList).then(() => {
                        this.changeHindText('[资产盘点]:盘点单[' + item.inventoryName + ']盘盈数据保存本地成功');
                    }).catch((err) => {
                        this.changeHindText('[资产盘点]:盘点单[' + item.inventoryName + ']盘盈数据保存本地失败:' + err + '', true);
                    });
                }
            });
            insertList(InventoryTableName, data).then(() => {
                this.changeHindText('[资产盘点]:盘点单数据保存本地成功');
            }).catch((err) => {
                this.changeHindText('[资产盘点]:盘点单数据保存本地失败:' + err + '', true);
            });
        } else {
            this.changeHindText('[资产盘点]:从服务器同步的盘点单数据为空');
        }
    }

    // 同步位置迁移数据
    syncMoveReasonData = async () => {
        // 先上传本地数据
        await queryAll(MoveLocationTableName).then((data) => {
            if (data.length > 0) {
                data.forEach(async (item, index) => {
                    let params = {
                        roomId: item.roomId,
                        moveReason: item.reasonId,
                        assetIdList: JSON.parse(item.assetIds)
                    }
                    this.changeHindText('[位置迁移]:正在上传第' + (index + 1) + '条数据...');
                    await HttpUtil.post('createMove', params).then(result => {
                        if (result.httpCode === 200) {
                            // 上传成功后删除本地数据
                            this.changeHindText('[位置迁移]:第' + (index + 1) + '条数据上传成功,删除本地数据中...');
                            deleteById(MoveLocationTableName, item.id).then(() => {
                                this.changeHindText('[位置迁移]:第' + (index + 1) + '条本地数据删除成功');
                            }).catch((err) => {
                                this.changeHindText('[位置迁移]:第' + (index + 1) + '条本地数据删除失败:' + err + '', true);
                            });
                        } else {
                            this.changeHindText('[位置迁移]:第' + (index + 1) + '条数据上传失败:' + result.msg + '', true);
                        }
                    }).catch((err) => {
                        this.changeHindText('[位置迁移]:第' + (index + 1) + '条数据上传失败:' + err + '', true);
                    });
                });
            } else {
                this.changeHindText('[位置迁移]:没有需要上传的数据');
            }
        }).catch((err) => {
            this.changeHindText('[位置迁移]:查询本地数据错误:' + err + '', true);
        });
    }
    back = () => {
        this.props.navigation.navigate('Main');
        this.props.navigation.state.params.callBack();
    }
    handleCheckboxToggle = (key) => {
        this.setState((prevState) => ({
            checkBoxData: prevState.checkBoxData.map((item) => {
                if (item.key === key) {
                    return { ...item, isChecked: !item.isChecked };
                }
                return item;
            }),
        }));
        console.log(this.state.checkBoxData)
    };
    renderItem(item) {
        return (
            <View style={styles.listItem}>
                <CheckBox
                    style={styles.checkbox}
                    value={item.isChecked}
                    onValueChange={() => this.handleCheckboxToggle(item.key)}
                />
                <Text style={styles.label}>{item.label}</Text>
            </View>
        )
    }
    renderTextItem = ({ item }) => (
        <View style={styles.item}>
            <Text style={styles.text}>{item}</Text>
        </View>
    );
    render() {
        return (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <View style={{ width: getPixel(55), justifyContent: 'center', alignItems: 'center' }}>
                        <TouchableOpacity onPress={() => this.back()}>
                            <Image source={require('../images/back.png')} style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                        </TouchableOpacity>
                    </View>
                    <View style={{ width: getScreenWidth() - getPixel(110), justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ fontSize: getPixel(17), color: '#333' }}>数据同步</Text>
                    </View>
                    <View style={{ width: getPixel(55), justifyContent: 'center', alignItems: 'center' }}>
                    </View>
                </View>
                <View style={styles.flatlist}>
                    <FlatList
                        data={this.state.checkBoxData}
                        renderItem={({ item }) => this.renderItem(item)}
                        keyExtractor={(item) => item.key}
                    />
                </View>
                <View style={styles.syncHint}>
                    <FlatList
                        ref={this.textFlatListRef}
                        data={this.state.syncHintText}
                        renderItem={({ item, index }) => <Text style={item.isError ? styles.errItemText : styles.firstItemText}>{item.text}</Text>}
                        keyExtractor={(item, index) => index.toString()}
                        initialScrollIndex={0}
                    />
                </View>
                <View style={styles.buttonGroup}>
                    <TouchableOpacity onPress={this.submit}>
                        <View style={DeviceInfo.getDeviceId() !== 'rk30sdk' ? styles.buttonSave : styles.buttonSaveAll}>
                            <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>同步</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </SafeAreaView>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    header: {
        height: getPixel(50),
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        flexDirection: 'row',
    },
    flatlist: {
        width: getScreenWidth(),
        backgroundColor: '#F5F5F5',
        padding: 5,
    },
    listItem: {
        width: getScreenWidth() - 20,
        flexDirection: 'row',
        alignItems: 'center',
        // marginBottom: 8,
    },
    checkbox: {
        transform: [{ scale: 1 }], // 调整勾选框的大小
    },
    label: {
        marginLeft: 8,
        fontSize: 18,
    },
    syncHint: {
        flex: 1,
        width: getScreenWidth(),
        backgroundColor: '#fff',
        textAlign: 'center',
        alignItems: 'center',
    },
    itemText: {
        fontSize: 16,
        lineHeight: 24,
        color: '#333',
        padding: 5,
    },

    firstItemText: {
        fontSize: 16,
        lineHeight: 24,
        color: '#333',
        padding: 5,
    },
    errItemText: {
        fontSize: 16,
        lineHeight: 24,
        color: '#ff0000',
        padding: 5,
    },

    buttonGroup: {
        flexDirection: 'row',
        paddingLeft: getPixel(15),
        paddingRight: getPixel(15),
        height: getPixel(60),
        backgroundColor: '#FFF',
        width: getScreenWidth(),
        alignItems: 'center',
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
    },
    buttonSave: {
        backgroundColor: '#4a69dd',
        height: getPixel(40),
        borderTopRightRadius: getPixel(10),
        borderBottomRightRadius: getPixel(10),
        width: (getScreenWidth() - 30) / 2,
    },
    buttonSaveAll: {
        backgroundColor: '#4a69dd',
        height: getPixel(40),
        borderRadius: getPixel(10),
        width: (getScreenWidth() - 30),
    },
});

